package com.marketingexpert.controller.personmgnt;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import weibo4j.User;

import com.marketingexpert.domain.UserType;
import com.marketingexpert.exception.MarketingExpertException;
import com.marketingexpert.service.snsmgnt.SnsService;
import com.marketingexpert.service.snsmgnt.SnsServiceFactory;
import com.marketingexpert.service.snsmgnt.tencent.TencentWeibo;
import com.marketingexpert.service.usermgnt.UserService;

public class GetTencentWeiboAccountController implements Controller {

	private static Logger logger = Logger.getLogger(GetTencentWeiboAccountController.class);
	
	private UserService userService;
	
	private SnsServiceFactory snsServiceFactory;
	
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		PrintWriter out = response.getWriter(); 
		response.setContentType("application/x-json;charset=GBK"); 
		response.setHeader("Pragma", "No-cache"); 
		response.setHeader("Cache-Control", "no-cache"); 
		response.setHeader("Cache-Control", "no-store"); 
		response.setDateHeader("Expires", 0);  
		
		String parentUserId = (String)request.getSession().getAttribute("parentUserId");
		List<com.marketingexpert.domain.User> myUsers = userService.queryUserByParentId(parentUserId);
		
		SnsService weboauth = getSnsServiceFactory().getService(SnsServiceFactory.TECENT);
		
		List<com.marketingexpert.service.snsmgnt.User> weiboUsers = new ArrayList<com.marketingexpert.service.snsmgnt.User>();
		
		Iterator<com.marketingexpert.domain.User> it = myUsers.iterator();

		try {
		for(;it.hasNext();) {
			com.marketingexpert.domain.User myUser = it.next();
			
			if(myUser.getUserType().equals(UserType.SINAWEIBO)) {
				continue;
			}
			com.marketingexpert.service.snsmgnt.User user = weboauth.getUserDetails(myUser.getAccessToken(), myUser.getSecret(),myUser.getUserId());
			weiboUsers.add(user);
			}
			JSONArray jsonList = JSONArray.fromObject(weiboUsers);

			out.print(jsonList);
			return null;
		} catch(Exception e) {
			logger.error(e.getMessage(),e);			
			out.print(JSONArray.fromObject("[]"));			
			return null;
		}
		
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public SnsServiceFactory getSnsServiceFactory() {
		return snsServiceFactory;
	}

	public void setSnsServiceFactory(SnsServiceFactory snsServiceFactory) {
		this.snsServiceFactory = snsServiceFactory;
	}
	
	

}
